package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import bean.LoggedUser;
import bean.Model;
import bean.UserType;
import dao.OperationResult;
import dao.PasswordDAO;
import formBean.PasswordForm;

public class ChangePasswordAction extends Action {

	private PasswordDAO passwordDAO = null;
	private FormBeanFactory<PasswordForm> formBeanFactory = FormBeanFactory.getInstance(PasswordForm.class);
	
	public ChangePasswordAction(Model model)
	{
		passwordDAO = model.getPasswordDAO();
	}
	
	@Override
	public String getName() {
		return "changePassword.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors",errors);
		try {
			PasswordForm form = formBeanFactory.create(request);
			request.setAttribute("form", form);
			if (!form.isPresent()) {
	            return "changePassword.jsp";
	        }
			errors.addAll(form.getValidationErrors());
			if(errors.size()>0)
			{
				return "changePassword.jsp";
			}
			else
			{
				LoggedUser user = (LoggedUser)request.getSession().getAttribute("user");
				if(!form.getOldPassword().equals(user.getPassword()) && !DigestUtils.md5Hex(user.getPassword()).equals(form.getOldPassword()))
				{
					errors.add("Old password is wrong!");
					return "changePassword.jsp";
				}
				OperationResult result;
				int id = Integer.parseInt(form.getUserId());
				if(user.getUserType().equals(UserType.Customer))
				{
					result = this.passwordDAO.updateCustomerPassword(form.getNewPassword(), id);
				}
				else
				{
					result = this.passwordDAO.updateEmployeePassword(form.getNewPassword(), id);
				}
				if(result.isSuccess())
				{
//					return util.Util.getDefaultPage(user.getUserType(), request);
					user.setPassword(form.getNewPassword());
					request.getSession().setAttribute("user", user);
					return "success.jsp";
				}
				else
				{
					errors.addAll(result.getErrorMessages());
					return "changePassword.jsp";
				}
			}
		} catch (FormBeanException e) {
			e.printStackTrace();
			return "changePassword.jsp";
		}
	}

	@Override
	public UserType getType() {
		return UserType.Both;
	}

}
